package com.lagou.rpc.consumer.client;

import com.lagou.rpc.consumer.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 1. 连接Netty服务
 * 2. 提供给调用者主动关闭资源的方法
 * 3. 提供消息发送的方法
 *
 */
public class RpcClient {

    private String ip;
    private int port;

    private RpcClientHandler rpcClientHandler = new RpcClientHandler();
    private ExecutorService executorService = Executors.newCachedThreadPool();

    NioEventLoopGroup group;
    Bootstrap bootstrap;
    Channel channel;

    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;

        initClent();
    }

    /**
     * 初始化方法-连接netty服务端
     */
    public void initClent(){
        try {
            group = new NioEventLoopGroup();
            bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE,Boolean.TRUE)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取管道
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //添加编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());

                            //客户端处理类-TDDO
                            pipeline.addLast(rpcClientHandler);

                        }
                    });
            channel = bootstrap.connect(ip, port).sync().channel();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void close(){
        if(group != null){
            group.shutdownGracefully();
        }

        if(channel != null){
            channel.close();
        }
    }

    public Object send(String msg ) throws ExecutionException, InterruptedException {
        rpcClientHandler.setRequestMessage(msg);
        Future submit = executorService.submit(rpcClientHandler);
        return submit.get();
    }


}
